import user from './user';
import home from './home';
import card from './card';
import pay from './pay';

const BASE_URL = "https://api.66member.com";
// 测试地址
// const BASE_URL = "http://localhost:8089";
// const BASE_URL = "http://192.168.3.10:8089";

const apiConfig = Object.assign({}, user, home, card, pay);

const api = {};
for (const key in apiConfig) {
	if (Object.prototype.hasOwnProperty.call(apiConfig, key)) {
		const {
			url
		} = apiConfig[key];
		api[key] = (data, options) => {
			return new Promise((resolve, reject) => {
				uni.request({
					method: 'POST',
					header: {
						...getApp() ? getApp().globalData['headerInfo'] : {},
						token: getApp() ? getApp().globalData['token'] : '',
						platform: getApp() ? getApp().globalData['platform'] : '',
					},
					...apiConfig[key],
					...options,
					url: BASE_URL + url,
					data,
					success: (res) => {
						// 网络请求错误
						console.log('res-', res)
						if (!res.data) {
							reject(new Error(res.errMsg || '请求失败！'));
						}
						// 业务错误(408未登录)
						if (Number(res.data.errno) === 408) {
							const error = new Error('请重新登录！')
							error.errno = res.data.errno;
							// 移除local
							uni.setStorageSync("user_token", '');
							// 移除globalData
							getApp().globalData["userInfo"] = {};
							reject(error);
						}
						if (Number(res.data.errno) !== 200) {
							const error = new Error(res.data.errMsg || '请求异常！')
							error.errno = res.data.errno;
							reject(error);
						}
						resolve(res.data.data)
					},
					fail: (err) => {
						reject(err)
					}
				});
			})
		}
	}
}
export default api;
